package com.yb.forum.services.impl;

import com.yb.forum.common.AppResult;
import com.yb.forum.common.ResultCode;
import com.yb.forum.dao.UserMapper;
import com.yb.forum.exception.ApplicationException;
import com.yb.forum.model.Board;
import com.yb.forum.model.User;
import com.yb.forum.services.IUserService;
import com.yb.forum.utils.MD5Util;
import com.yb.forum.utils.RedisCacheUtil;
import com.yb.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    private static final String USER_CACHE_PREFIX_BY_ID = "user:id:";
    private static final String USER_CACHE_PREFIX_BY_USERNAME = "user:username:";
    private static final long CACHE_EXPIRE_SECONDS = 3600;

    @Override
    public void createNormalUser(User user) {
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            log.warn("参数校验失败: {}", ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        String username = user.getUsername();
        String usernameKey = USER_CACHE_PREFIX_BY_USERNAME + username;

        // 先查缓存
        User existingUser = redisCacheUtil.getCacheObject(usernameKey, User.class);
        if (existingUser == null) {
            existingUser = userMapper.selectByUserName(username);
            if (existingUser != null) {
                redisCacheUtil.setCacheObject(usernameKey, existingUser, CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
            }
        }

        if (existingUser != null) {
            log.info("用户名已存在: {}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        int rows = userMapper.insertSelective(user);
        if (rows != 1) {
            log.error("创建用户失败: username={}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info("创建用户成功: username={}", username);
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            log.warn("用户名为空");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        String key = USER_CACHE_PREFIX_BY_USERNAME + username;
        User user = redisCacheUtil.getCacheObject(key, User.class);
        if (user != null) {
            log.debug("命中 Redis 缓存 (by username): {}", username);
            return user;
        }

        user = userMapper.selectByUserName(username);
        if (user != null) {
            redisCacheUtil.setCacheObject(key, user, CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
            log.debug("从数据库加载用户并缓存: {}", username);
        }

        return user;
    }

    @Override
    public User login(String username, String password) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn("登录参数为空");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        User user = selectByUserName(username);
        if (user == null) {
            log.warn("登录失败：用户不存在, username={}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn("登录失败：密码错误, username={}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn("用户ID为空");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        String key = USER_CACHE_PREFIX_BY_ID + id;
        User user = redisCacheUtil.getCacheObject(key, User.class);
        if (user != null) {
            log.debug("命中 Redis 缓存 (by id): {}", id);
            return user;
        }

        user = userMapper.selectByPrimaryKey(id);
        if (user != null) {
            redisCacheUtil.setCacheObject(key, user, CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
            log.debug("从数据库加载用户并缓存: {}", id);
        }
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        // 查询出用户信息（直接查 DB，避免缓存脏读）
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " user_id is " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setArticleCount(user.getArticleCount() + 1);

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        // ✅ 关键：清除 Redis 缓存，保证一致性
        String cacheKey = USER_CACHE_PREFIX_BY_ID + id;
        redisCacheUtil.delete(cacheKey);

        log.debug("用户发帖数更新成功并清除缓存: id={}", id);
    }
}